import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np

from CLIP import clip

class ResidualBlock(nn.Module):
    """Residual Block with instance normalization."""
    def __init__(self, dim_in, dim_out):
        super(ResidualBlock, self).__init__()
        self.main = nn.Sequential(
            nn.Conv2d(dim_in, dim_out, kernel_size=3, stride=1, padding=1, bias=False),
            nn.InstanceNorm2d(dim_out, affine=True, track_running_stats=True),
            nn.ReLU(inplace=True),
            nn.Conv2d(dim_out, dim_out, kernel_size=3, stride=1, padding=1, bias=False),
            nn.InstanceNorm2d(dim_out, affine=True, track_running_stats=True))

    def forward(self, x):
        return x + self.main(x)


class ClipEncoder(nn.Module):
    def __init__(self, clip_model_name="RN50", device="cuda:0"):
        super(ClipEncoder, self).__init__()
        self.device = device
        assert clip_model_name in clip.available_models(), f"not avialable model {clip_model_name}"
        self.clip_model, self.clip_preprocess = clip.load(clip_model_name, device=device, jit=False)
    
    def forward(self, x):
        with torch.no_grad():
            # img = self.clip_preprocess(img)
            if isinstance(x, list):
                x = clip.tokenize(x).to(self.device)
                code = self.clip_model.encode_text(x)
            else:
                x = x.to(self.device)
                code = self.clip_model.encode_image(x)
        # print(code.shape)
        return code.float()

class Generator(nn.Module):
    """Generator network."""
    def __init__(self, emb_dim=1024, conv_dim=64, repeat_num=6):
        super(Generator, self).__init__()

        self.mlp1 = nn.Linear(emb_dim, conv_dim)
        self.mlp2 = nn.Linear(emb_dim, conv_dim * 2)
        self.mlp3 = nn.Linear(emb_dim, conv_dim * 4)
        self.act = nn.Sigmoid()

        self.levels = nn.ModuleList()
        self.levels.append(
            nn.Sequential(
                nn.Conv2d(3, conv_dim, kernel_size=7, stride=1, padding=3, bias=False),
                nn.InstanceNorm2d(conv_dim, affine=True, track_running_stats=True),
                nn.ReLU(inplace=True)
            )
        )

        # Down-sampling layers.
        curr_dim = conv_dim
        for i in range(2):
            self.levels.append(
                nn.Sequential(
                    nn.Conv2d(curr_dim, curr_dim*2, kernel_size=4, stride=2, padding=1, bias=False),
                    nn.InstanceNorm2d(curr_dim*2, affine=True, track_running_stats=True),
                    nn.ReLU(inplace=True)
                )
            )
            curr_dim = curr_dim * 2

        layers = []
        # Bottleneck layers.
        for i in range(repeat_num):
            layers.append(ResidualBlock(dim_in=curr_dim, dim_out=curr_dim))

        # Up-sampling layers.
        for i in range(2):
            layers.append(nn.ConvTranspose2d(curr_dim, curr_dim//2, kernel_size=4, stride=2, padding=1, bias=False))
            layers.append(nn.InstanceNorm2d(curr_dim//2, affine=True, track_running_stats=True))
            layers.append(nn.ReLU(inplace=True))
            curr_dim = curr_dim // 2

        layers.append(nn.Conv2d(curr_dim, 3, kernel_size=7, stride=1, padding=3, bias=False))
        layers.append(nn.Tanh())
        self.main = nn.Sequential(*layers)

    def forward(self, x, c):
        # Replicate spatially and concatenate domain information.
        # Note that this type of label conditioning does not work at all if we use reflection padding in Conv2d.
        # This is because instance normalization ignores the shifting (or bias) effect.
        c1 = self.act(self.mlp1(c))
        c2 = self.act(self.mlp2(c))
        c3 = self.act(self.mlp3(c))
        cc = [t.view(t.size(0), t.size(1), 1, 1) for t in [c1, c2, c3]]
        x1 = self.levels[0](x) * cc[0] 
        x2 = self.levels[1](x1) * cc[1]
        x3 = self.levels[2](x2) * cc[2]
        return self.main(x3)


class Discriminator(nn.Module):
    """Discriminator network with PatchGAN."""
    def __init__(self, image_size=128, conv_dim=64, emb_dim=1024, repeat_num=6):
        super(Discriminator, self).__init__()
        layers = []
        layers.append(nn.Conv2d(3, conv_dim, kernel_size=4, stride=2, padding=1))
        layers.append(nn.LeakyReLU(0.01))

        curr_dim = conv_dim
        for i in range(1, repeat_num):
            layers.append(nn.Conv2d(curr_dim, curr_dim*2, kernel_size=4, stride=2, padding=1, bias=False))
            layers.append(nn.BatchNorm2d(curr_dim*2, affine=True))
            layers.append(nn.LeakyReLU(0.01))
            curr_dim = curr_dim * 2

        kernel_size = int(image_size / np.power(2, repeat_num))
        self.main = nn.Sequential(*layers)
        self.conv1 = nn.Conv2d(curr_dim, 1, kernel_size=3, padding=1, stride=1, bias=False)
        self.act1 = nn.Sigmoid()
        self.conv2 = nn.Conv2d(curr_dim, emb_dim, kernel_size=kernel_size, bias=False)

        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                nn.init.xavier_normal_(m.weight.data)
                if m.bias is not None:
                    nn.init.constant_(m.bias.data, 0.0)
            elif isinstance(m, nn.BatchNorm2d):
                m.weight.data.fill_(1)
                m.bias.data.zero_()
        
    def forward(self, x):
        h = self.main(x)
        out_src = self.act1(self.conv1(h))
        out_emb = self.conv2(h)
        return out_src, out_emb.view(out_emb.size(0), out_emb.size(1))
